using Eneta.Portal.Forum.Common.Data;
using Eneta.Portal.Forum.Core.Domain.Collections;
using Eneta.Portal.Forum.Core.Domain.Entities;
using Eneta.Portal.Forum.Core.Service.Application;

namespace Eneta.Portal.Forum.Core.Data
{
    public class GroupDao : DataProviderBase
    {
        /// <summary>
        /// Finds the by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Group FindById(int id)
        {
            SharePointListItem listItem = Provider.GetListItembyID(ForumConstants.Lists_Groups, id);
            var group = new Group();
            group.Id = listItem.Id;
            group.Name = listItem["Title"];
            return group;
        }

        /// <summary>
        /// Gets all.
        /// </summary>
        /// <returns></returns>
        public GroupCollection GetAll()
        {
            var groups = new GroupCollection();
            SharePointListDescriptor items = Provider.GetAllListItems(ForumConstants.Lists_Groups);

            foreach (SharePointListItem listItem in items.SharePointListItems)
            {
                groups.Add(new Group(listItem.Id, listItem["Title"]));
            }

            return groups;
        }

        /// <summary>
        /// Saves the specified group.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <returns></returns>
        public int Save(Group group)
        {
            string[] values = {
                                  "Title", group.Name,
                              };
            SharePointListItem listItem = new SharePointListItem(group.Id, values);

            if (group.Id == 0)
                return Provider.AddListItem(ForumConstants.Lists_Groups, listItem);
            
            return Provider.UpdateListItem(ForumConstants.Lists_Groups, listItem);
        }
    }
}